package jEDF.FFT;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

import jEDF.EDF.*;
import jEDF.JEDF.*;
import projetotcc2.ProjetoTCC2View;

/**
 *
 * <p>Titre : jEDF</p>
 * <p>Description : Java European Data Format Viewer and Analyser</p>
 * <p>Author : Nizar Kerkeni</p>
 * <p>Copyright : Copyright (c) 2003-2006</p>
 * <p>Version 2.0</p>
 */
public class FFTExportDialog extends JDialog {

    private JLabel jlChannel = new JLabel(JEDFMainWindow.getLocalizedString("Channel"));
    private JComboBox jcbSignals = new JComboBox();
    private JLabel jlDuration = new JLabel(JEDFMainWindow.getLocalizedString("By duration (s)"));
    private JTextField jtfDuration = new JTextField("2");
    private JLabel jlFrom = new JLabel(JEDFMainWindow.getLocalizedString("Epochs from"));
    private JTextField jtfFrom = new JTextField("1");
    private JLabel jlTo = new JLabel(JEDFMainWindow.getLocalizedString("to"));
    private JTextField jtfTo = new JTextField();
    private JLabel jlOutputType = new JLabel(JEDFMainWindow.getLocalizedString("Output type :"));
    private JRadioButton jrbSleepBands = new JRadioButton(JEDFMainWindow.getLocalizedString("Sleep bands"));
    private JRadioButton jrb1Hz = new JRadioButton("1 Hz");
    private ButtonGroup buttonGroup = new ButtonGroup();
    private JLabel jlFile = new JLabel(JEDFMainWindow.getLocalizedString("Output file"));
    private JTextField jtfFile = new JTextField();
    private JButton jbBrowse = new JButton(JEDFMainWindow.getLocalizedString("Browse"));
    private JProgressBar jProgressBar = new JProgressBar();
    private JButton jbOK = new JButton(JEDFMainWindow.getLocalizedString("OK"));
    private JButton jbCancel = new JButton(JEDFMainWindow.getLocalizedString("Cancel"));
    private String subName = null;
    private String oneHzString = "1Hz";
    private String sleepBString = "SB";
    private ProjetoTCC2View mainWindow = null;

    public FFTExportDialog(ProjetoTCC2View mainWindow,
            Polysomnograph polysomnograph) {
        super(mainWindow.getFrame(), true);

        this.mainWindow = mainWindow;

        EDFFile edfFile = mainWindow.getEdfFile();

        if (edfFile == null) {
            return;
        }

        JEDFGraph[] graphs = polysomnograph.getAllGraphs();
        for (int i = 0; i < graphs.length; i++) {
            jcbSignals.addItem(graphs[i].getSignal());
        }

        jtfTo.setText(edfFile.getNbRecords() + "");
        jtfDuration.setColumns(4);
        jtfFrom.setColumns(4);
        jtfTo.setColumns(4);
        jtfFile.setColumns(20);

        jrb1Hz.setActionCommand(oneHzString);
        jrbSleepBands.setActionCommand(sleepBString);
        buttonGroup.add(jrb1Hz);
        buttonGroup.add(jrbSleepBands);
        jrbSleepBands.setSelected(true);
        subName = "SB";

        jProgressBar.setStringPainted(true);

        jrb1Hz.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                onRadionButtonSelection(ae);
            }
        });

        jrbSleepBands.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                onRadionButtonSelection(ae);
            }
        });

        jbCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        jbBrowse.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                browseButtonClicked();
            }
        });

        jbOK.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                okButtonClicked();
            }
        });

        jcbSignals.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                onComboBoxSelection();
            }
        });

        organize();

        onComboBoxSelection();

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void organize() {
        JPanel clientArea = new JPanel();
        clientArea.setLayout(new BoxLayout(clientArea, BoxLayout.Y_AXIS));

        JPanel jPanel = new JPanel();
        jPanel.add(jlChannel);
        jPanel.add(jcbSignals);
        clientArea.add(jPanel);

        jPanel = new JPanel();
        jPanel.add(jlDuration);
        jPanel.add(jtfDuration);
        clientArea.add(jPanel);

        jPanel = new JPanel();
        jPanel.add(jlFrom);
        jPanel.add(jtfFrom);
        jPanel.add(jlTo);
        jPanel.add(jtfTo);
        clientArea.add(jPanel);

        jPanel = new JPanel();
        jPanel.add(jlOutputType);
        jPanel.add(jrbSleepBands);
        jPanel.add(jrb1Hz);
        clientArea.add(jPanel);

        jPanel = new JPanel();
        jPanel.add(jlFile);
        jPanel.add(jtfFile);
        jPanel.add(jbBrowse);
        clientArea.add(jPanel);

        clientArea.add(jProgressBar);

        jPanel = new JPanel();
        jPanel.add(jbOK);
        jPanel.add(jbCancel);
        clientArea.add(jPanel);

        setContentPane(clientArea);
    }

    private void browseButtonClicked() {
        File file = new File(jtfFile.getText());
        JFileChooser chooser = new JFileChooser();
        chooser.setSelectedFile(file);

        String[] extensions = {"fft"};

        EDFFileFilter edfFileFilter = new EDFFileFilter(extensions,
                JEDFMainWindow.getLocalizedString("FFT text file"));

        chooser.setFileFilter(edfFileFilter);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            EDFFileFilter.changeFileExtension(chooser.getSelectedFile(), "");
            String chosenFile = chooser.getSelectedFile().getAbsolutePath();

            if (!chosenFile.endsWith(".fft")) {
                chosenFile += ".fft";
            }

            jtfFile.setText(chosenFile);
        }
    }

    private void okButtonClicked() {
        File file = new File(jtfFile.getText());

        int startTime = 0;
        int endTime = 0;
        int duration = 0;

        try {
            duration = new Integer(jtfDuration.getText().trim()).intValue();

            startTime = new Integer(jtfFrom.getText().trim()).intValue();
            endTime = new Integer(jtfTo.getText().trim()).intValue();

            if (file.exists()) {
                int result = JOptionPane.showConfirmDialog(this,
                        JEDFMainWindow.getLocalizedString(
                        "The specified file already exists.\nAre you sure you want to replace its content ?"),
                        JEDFMainWindow.getLocalizedString("Warning"),
                        JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION) {
                    return;
                }
                file.delete();
            }

            EDFSignal signal = (EDFSignal) jcbSignals.getSelectedItem();

            if (signal == null) {
                return;
            }

            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

            if (jrbSleepBands.isSelected()) {
                signal.fftToTextBySleepBands(this, file, startTime - 1, endTime,
                        duration);
            } else {
                signal.fftToText1Hz(this, file, startTime - 1, endTime,
                        duration);
            }

            jbOK.setEnabled(false);
            jbBrowse.setEnabled(false);
            jtfDuration.setEnabled(false);
            jtfFrom.setEnabled(false);
            jtfTo.setEnabled(false);
            jtfFile.setEnabled(false);
            jcbSignals.setEnabled(false);
            jrb1Hz.setEnabled(false);
            jrbSleepBands.setEnabled(false);

        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "Please verify that you have entered valid parameters."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "Please verify that you have entered valid parameters."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void onComboBoxSelection() {
        EDFFile edfFile = mainWindow.getEdfFile();

        if (edfFile == null) {
            return;
        }

        String selectedValue = jcbSignals.getSelectedItem().toString();
        String fileName = EDFFileFilter.changeFileExtension(edfFile.getFile(), "_" + selectedValue + "_" + subName + ".fft");

        jtfFile.setText(fileName);
    }

    private void onRadionButtonSelection(ActionEvent e) {
        subName = e.getActionCommand();
        onComboBoxSelection();
    }

    /**
     * @return Returns the jProgressBar.
     */
    public JProgressBar getJProgressBar() {
        return jProgressBar;
    }
}
